package com.spzx.product;

import com.spzx.common.security.annotation.EnableCustomConfig;
import com.spzx.common.security.annotation.EnableRyFeignClients;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

import java.util.List;

/*
* 商品微服务启动,需要将商品Sku数据存在与否以Bitmap数据结构存储起来,解决缓存穿透问题
*/
@EnableCustomConfig
//自定义配置注解,可能启用也定功能(安全配置,Feign客户端等等)
@EnableRyFeignClients
//启用Feign客户端,用于服务间通信(eg.调用其他微服务接口)
@SpringBootApplication
//SpringBoot核心注解,包含@EnableAutoConfiguration---自动配置 @ComponentScan---组件扫描 @Configuration---主配置类

//CommandLineRunner是SpringBoot提供的
public class SpzxProductApplication  implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(SpzxProductApplication.class, args);
        System.out.println("(♥◠‿◠)ﾉﾞ  系统模块启动成功   ლ(´ڡ`ლ)ﾞ  \n" +
                " .-------.       ____     __        \n" +
                " |  _ _   \\      \\   \\   /  /    \n" +
                " | ( ' )  |       \\  _. /  '       \n" +
                " |(_ o _) /        _( )_ .'         \n" +
                " | (_,_).' __  ___(_ o _)'          \n" +
                " |  |\\ \\  |  ||   |(_,_)'         \n" +
                " |  | \\ `'   /|   `-'  /           \n" +
                " |  |  \\    /  \\      /           \n" +
                " ''-'   `'-'    `-..-'              ");
    }

    @Autowired
    ProductSkuMapper productSkuMapper;

    @Autowired
    RedisTemplate redisTemplate;

    //服务器启动时执行初始化:构建商品的bitmap
    //Bitmap(位图)优点:解决缓存穿透问题;不存储数据本身,只存储标记(占用内存空间小且安全),结构简单:二进制拼成字符串
    //应用启动时,将数据库中所有商品Sku的id写入Redis的Bitmap,标记商品的id
    @Override
    public void run(String... args) throws Exception {
        String dataKey ="sku:product:data";
        //从数据库中查询所有商品的SkuId
        List<ProductSku> productSkuList= productSkuMapper.selectList(null);
        if(!CollectionUtils.isEmpty(productSkuList)){
            productSkuList.forEach(productSku -> {
                redisTemplate.opsForValue().setBit(dataKey,productSku.getId(),true);
            });
        }
        /*
         for (ProductSku productSku : productSkuList) {
         redisTemplate.opsForValue().setBit(dataKey, productSku.getId(), true);
         }
         */
    }
}
